package com.dcy.znoa.common.resolver;

import com.alibaba.fastjson.JSONObject;
import com.dcy.znoa.common.bean.Result;
import com.dcy.znoa.common.enums.ResultCode;
import com.dcy.znoa.common.exception.BusinessException;
import com.dcy.znoa.common.util.pojo.JsonCommon;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.SystemException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component("exceptionResolver")
public class GlobleExceptionResolver implements HandlerExceptionResolver {

    private static final String ERROR_VIEW = "error";

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response, Object handler, Exception ex) {

        JsonCommon result = null;
        if (BusinessException.class.isAssignableFrom(ex.getClass())) {
            BusinessException bex = (BusinessException) ex;
            result = new JsonCommon(bex.getErrorCode(), bex.getErrorMsg());

            log.error("HandlerExceptionResolver catch the Business Exception -> {}", bex.getErrorMsg(), ex);
        } else if (SystemException.class.isAssignableFrom(ex.getClass())) {
            // 系统异常-严重
            result = new JsonCommon(JsonCommon.SERVICE_ERROR_CODE, JsonCommon.SERVICE_ERROR_MSG);
            log.error("HandlerExceptionResolver catch the System Exception -> {}", ex.getMessage(), ex);
        } else {	//未捕获到的异常，级别非常严重
            result = new JsonCommon(JsonCommon.SERVICE_ERROR_CODE, JsonCommon.SERVICE_ERROR_MSG);
            log.error("HandlerExceptionResolver catch the serious System Exception -> {} ", ex);
        }

        String requestHeader = request.getHeader("Accept");
        response.setCharacterEncoding("UTF-8");

        if (requestHeader == null || isAjaxHandler(handler)) {
            // 返回json格式的数据xx
            try {
                response.setContentType("application/json;charset=UTF-8");
                StringBuffer responseSb = new StringBuffer();

                responseSb.append(JSONObject.toJSONString(result));

                response.getWriter().println(responseSb.toString());
            } catch (Exception e) {
                log.error("Response write exception", e);
            }

            return new ModelAndView();
        } else {
            //TODO 此处以后需要重新设计， 如果是业务异常返回404，如果是系统异常或为捕获的异常返回500
            response.setContentType("text/html;charset=UTF-8");
            request.setAttribute("code", result.getCode());
            request.setAttribute("msg", result.getMsg());
            return new ModelAndView(ERROR_VIEW);	//此处需要准备一个404页面
        }
    }
    private boolean isAjaxHandler(Object handler) {
        if(handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            Class<?> beanType = handlerMethod.getBeanType();
            return beanType.getAnnotation(RestController.class)!= null
                    || beanType.getAnnotation(ResponseBody.class)!= null
                    || handlerMethod.getMethodAnnotation(ResponseBody.class) != null || (handlerMethod.getMethod().getReturnType().isAssignableFrom(Result.class));
        }
        return false;
    }
}
